package com.example.websocket.controller;


import com.alibaba.fastjson.JSON;
import com.example.websocket.pojo.Result;
import com.example.websocket.pojo.ws.ResultMessage;
import com.example.websocket.pojo.dto.MessageDto;
import com.example.websocket.pojo.dto.UserListDto;
import com.example.websocket.service.MessageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.example.websocket.constants.Constants.MESSAGE_KEY;


/**
 * @ author 韩
 * time: 2024/3/6 23:59
 */
@RestController
@RequestMapping("/message")
@Tag(name = "MessageController",description = "主要是对消息列表做的一系列操作")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Operation(summary = "主要是初始化的时候调用 获取消息列表")
    @GetMapping("/getMessageList")
    public Result getMessageList(String username) {
        List<UserListDto> messageList = messageService.getMessageList(username);
        return Result.ok(messageList);
    }

    @Operation(summary = "增添一条消息到消息列表")
    @PostMapping("/addMessage")
    public Result addMessage(@RequestBody MessageDto dto) {
        Boolean flag = messageService.addMessage(dto);
        if (flag) {
            return Result.ok();
        }else {
            return Result.error();
        }
    }

    @Operation(description = "废弃",summary = "根据时间戳来删除聊天数据,废弃转移到ws里")
    @DeleteMapping("/revokeMessage")
    public Result revokeMessage(@RequestBody ResultMessage message) {
        Long remove = redisTemplate.opsForZSet().remove(MESSAGE_KEY,JSON.toJSONString(message));
        return Result.ok(remove);
    }

    @Operation(summary = "根据关键字来搜索消息的接口")
    @GetMapping("/searchMessage")
    public Result searchMessage(HttpSession session, @RequestParam("key")String key) {
        String username = (String)session.getAttribute("username");
        List<UserListDto> friends = messageService.searchMessage(username,key);
        return Result.ok(friends);
    }
}
